﻿var DetailValidationClientSideHide = false;
var PageNumber = 1;
var IsSearchView = false;
var DetailIDView = 0;
var IsDeleteView = false;
var ChangeElementID = 0;
var DetailComElem = null;
var DetailComElemVal = null;
var DetailTimerId = null;
$(document).ready(function () {
    var path = window.location.pathname;
    if (path.indexOf("SetupDetail") != -1) {
        $.validator.addMethod("SetupDetailRequireds", $.validator.methods.required, Messages["SetupDetailRequireds"]);
        $.validator.addMethod("SetupDetailMaxLength50", $.validator.methods.maxlength, Messages["SetupDetailMaxLength50"]);
        $.validator.addMethod("SetupDetailMaxLength20", $.validator.methods.maxlength, Messages["SetupDetailMaxLength20"]);
        $.validator.addClassRules({
            Required: {
                SetupDetailRequireds: true,
            },
            MaxLength50: {
                SetupDetailMaxLength50: 50,
            },
            MaxLength20: {
                SetupDetailMaxLength20: 20,
            },
        });

        $('#LoadDetailDetailsForm').validate();
        LoadDetailGrid();
    }
});
$(document).on('change', '.ChangedDetailElements', function () {
    $('#DetailDetailsSaveBtn').addClass('BackColorRed');
});
$(document).on('change', '.DetailAddElementChange', function () {
    $('#DetailAddBtn').addClass('BackColorRed');
});
function DeleteDetail(DetailID) {
    jConfirm('Are you sure you want to delete this Detail?', 'Warning!', function (retVal) {
        if (retVal == true) {
            DetailIDView = DetailID;
            IsDeleteView = true;
            LoadDetailGrid();
        }
    });
}
function AddNewDetail() {
    DetailValidationClientSideHide = false;
    $.ajax({
        url: urls["SetupAddNewDetail"],
        type: 'GET',
        success: function (data) {
            $("#AddNewDetailDiv").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            IsDeleteView = false;
            AddNewDetailPopUp("AddNewDetailDiv");
        }
    });
}
$(document).on('click', '#DetailMoreBtn', function () {
    PageNumber = PageNumber + 1;
    IsDeleteView = false;
    LoadDetailGrid();
});
$(document).on('click', '#DetailSearchBtn', function () {
    IsSearchView = true;
    IsDeleteView = false;
    LoadDetailGrid();
});
function AddNewDetailPopUp(PopUpDiv) {
    $.colorbox({
        width: "600px",
        height: "330px",
        inline: true,
        href: "#" + PopUpDiv,
        onComplete: function () {
            $("#" + PopUpDiv).show();
        },
        onClosed: function () {
            $("#" + PopUpDiv).hide();
        }
    });
}
$(document).on('click', '#DetailAddBtn', function () {
    var $form = $('#AddNewDetailForm');
    if ($form.valid()) {
        DetailValidationClientSideHide = false;
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            beforeSend: function (xhr) {
                xhr.overrideMimeType('text/plain; charset=x-user-defined');
            },
            success: function (data) {
                if (data.indexOf("Error") != -1)
                    jAlert(data, "Error");
            },
            error: function (xhr) {
                jAlert(xhr.statusText, "Error");
            },
            complete: function () {
                $('#DetailAddBtn').removeClass('BackColorRed')
                jAlert("Data SuccessFully Saved:", "Successful");
                $('#cboxClose').click();
                IsDeleteView = false;
                LoadDetailGrid();
            }
        });
    }
    else
        DetailValidationClientSideHide = true;
});
$(document).on('click', '#DetailDetailsSaveBtn', function () {
        var $form = $('#LoadDetailDetailsForm');
        if ($form.valid()) {
            if ($form[0].length > 0) {
                $.ajax({
                    url: $form.attr('action'),
                    type: $form.attr('method'),
                    data: $form.serialize(),
                    beforeSend: function (xhr) {
                        xhr.overrideMimeType('text/plain; charset=x-user-defined');
                    },
                    success: function (data) {
                        if (data.indexOf("Error") != -1)
                            jAlert(data, "Error");
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        $('#DetailDetailsSaveBtn').removeClass('BackColorRed')
                        jAlert("Data SuccessFully Saved:", "Successful");
                        IsDeleteView = false;
                        LoadDetailGrid();
                    }
                });
            }
            else
                jAlert("You have not data to save:", "Attention!");
        }
});
function LoadDetailGrid() {
    var SetupDetailsGridViewModel = {
        SelectedDetailDetailTypeIDText: $("#SelectedDetailDetailTypeIDText").val(),
        DetailDescriptionText: $("#DetailDescriptionText").val(),
        DetailCodeText: $("#DetailCodeText").val(),
        PageNum: parseInt(PageNumber),
        IsSearch: IsSearchView,
        IsDelete: IsDeleteView,
        DetailID: parseInt(DetailIDView),
        IsActiveSearch: $("#IsActiveSearch").val(),
    };

    var DTO = JSON.stringify(SetupDetailsGridViewModel);
    $.ajax({
        url: urls["SetupLoadDetailsGrid"],
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: DTO,
        success: function (data) {
            $("#SetupDetailGrid").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            DetailElementsDrop();
        }
    });
}
function DetailElementsDrop()
{
    $(".DetailElementsDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
}
$(document).on('change', '.DetailElementsDrop', function () {
    $(".DetailElementsDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
});
$(document).on('change', '.DetailTypeDrop', function () {
    $(".DetailTypeDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
        var element = $(this).parent();
        var tdparent = element.parent();
    });
    var element = $(this).parent();
    var tdparent = element.parent();
    $.ajax({
        url: urls["SetupGetServiceByDetailID"],
        data: { DetailID: parseInt($(this).val()) },
        cache: false,
        type: "POST",
        success: function (data) {
            var markup = "<option value='0'>Select</option>";
            for (var x = 0; x < data.length; x++) {
                markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
            }
            $(tdparent).find("Select.ForChangeSeriveTypesFromDetailTypes").html(markup).show();
            $(tdparent).find("Select.ForChangeSeriveTypesFromDetailTypesImit").html(markup);
        },
        error: function (reponse) {
            jAlert(reponse, "Error");
        },
        complete: function () {
            DetailElementsDrop();
        }
    });
});

$(document).on('change', '.AddDetailTypeDrop', function () {
    $(".AddDetailTypeDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
        $(elem).next().valid();
    });
    var element = $(this).parent();
    var tdparent = element.parent();
    $.ajax({
        url: urls["SetupGetServiceByDetailID"],
        data: { DetailID: parseInt($(this).val()) },
        cache: false,
        type: "POST",
        success: function (data) {
            var markup = "<option value='0'>Select</option>";
            for (var x = 0; x < data.length; x++) {
                markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
            }
            $("Select.AddForChangeSeriveTypesFromDetailTypes").html(markup).show();
            $("Select.AddForChangeSeriveTypesFromDetailTypesImit").html(markup);
        },
        error: function (reponse) {
            jAlert(reponse, "Error");
        },
        complete: function () {
        }
    });
});
$(document).on('change', '.AddDetailDetailTypeDrop', function () {
    $(".AddDetailDetailTypeDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
});
$(document).on('change', '.AddDetailServiceTypeDrop', function () {
    $(".AddDetailServiceTypeDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
});
// text element complete text 
$(document).on('input', '.QuotaTxtComplete', function () {
    if (DetailTimerId == null) {
        DetailComElem = $(this).attr('id');
        DetailComElemVal = $("#" + DetailComElem).val();
        DetailTimerId = setInterval(function () {

            var keyword = $("#" + DetailComElem).val();
            if (keyword == DetailComElemVal) {
                var PropName = "";
                if (DetailComElem.indexOf("DetailCodeText") != -1)
                    PropName = "DetailCodeText";
                if (DetailComElem.indexOf("DetailDescriptionText") != -1)
                    PropName = "DetailDescriptionText";

                var position = $("#" + DetailComElem).offset();
                position.top = position.top + $("#" + DetailComElem).height() + 5;
                $.ajax({
                    url: urls["SetupAutoComplete"],
                    data: { 'PropName': PropName, 'keyword': keyword },
                    type: 'POST',
                    success: function (data) {
                        $("#AutoCompleteDiv").html(data);
                        var width = $("#" + DetailComElem).css("width");
                        $("#AutoCompleteDiv").css("width", width);
                        $("#AutoCompleteDiv").show();
                        $("#AutoCompleteDiv").offset(position);
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        clearInterval(DetailTimerId);
                        DetailTimerId = null;
                    }
                });
            }
            else
                DetailComElemVal = keyword;
        }, 600);
    }
});
$(document).on('click', '.QuotaAutoCompleteDivClose', function () {
    $(this).parent().parent().hide();
});
function htmlDecode(value) {
    return $('<div/>').html(value).text();
}
function AutoCompleteRowClick(key, val) {
    val = htmlDecode(val);
    $("#" + DetailComElem).val(val);
    if (DetailComElem.indexOf("DetailCodeText") != -1)
        $("#" + DetailComElem).next().val(key);
    if (DetailComElem.indexOf("DetailDescriptionText") != -1)
        $("#" + DetailComElem).next().val(key);
    $("#AutoCompleteDiv").hide();
}


var originalClose = $.colorbox.close;
$.colorbox.close = function () {
    if ($('#DetailAddBtn').hasClass('BackColorRed')) {
        jConfirm(Messages["ClosePopUp"], Messages["ClosePopUpTitle"], function (retVal) {
            if (retVal == true) {
                $("#AddNewDetailForm").empty();
                LoadDetailGrid();
                originalClose();
            }
        });
    }
    else {
        $("#AddNewDetailForm").empty();
        LoadDetailGrid();
        originalClose();
    }
};
$(document).on('change', '.ElementsForValidation', function () {
    if ($(this).valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
    if (DetailValidationClientSideHide) {
        if ($(this).closest("form").valid()) {
            $(this).closest("form").find("#errorMessageClient").text("");
        }
    }
    else if ($(this).valid()) {
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            $(this).valid();
        });
    }
});
$(document).on('change', '.ForValidation', function () {
    if ($(this).valid)
        $(this).removeClass('table_inputs_Unvalidated');
    if ($(this).closest("form").valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            if ($(this).valid())
                $(this).removeClass('table_inputs_Unvalidated');
        });
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
});